import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { formatMessage, FormattedMessage } from 'umi/locale';
import { Row, Col, Button, Form, Modal, Input, Select } from 'antd';

import styles from './index.less';

const FormItem = Form.Item;
const { TextArea } = Input;
const { Option } = Select;

const EditForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    handleModalVisible,
    handleEdit,
    protocolInfo,
    encoderList,
    decoderList,
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleEdit(fieldsValue, form);
    });
  };
  const renderOption = data =>
    data.map(item => (
      <Option key={item.id} value={item.id}>
        {item.name}
      </Option>
    ));
  return (
    <Modal
      title={formatMessage({ id: 'app.dm.product.edit' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem style={{ marginBottom: 0, marginTop: 0 }}>
          {form.getFieldDecorator('id', { initialValue: protocolInfo.id })(<Input type="hidden" />)}
        </FormItem>
        <FormItem style={{ marginBottom: 0, marginTop: 0 }}>
          {form.getFieldDecorator('productId', { initialValue: protocolInfo.productId })(
            <Input type="hidden" />,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.protocol.info.name' })} colon={false}>
          {form.getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.protocol.info.name.place' }),
              },
            ],
            initialValue: protocolInfo.name,
          })(
            <Input
              placeholder={formatMessage({ id: 'app.dm.product.protocol.info.name.place' })}
            />,
          )}
        </FormItem>

        <FormItem label={formatMessage({ id: 'app.dm.product.protocol.info.label' })} colon={false}>
          {form.getFieldDecorator('label', {
            initialValue: protocolInfo.label,
          })(<Input disabled />)}
        </FormItem>

        <FormItem
          label={formatMessage({ id: 'app.dm.product.protocol.info.protocoltype' })}
          colon={false}
        >
          {form.getFieldDecorator('protocolTypeName', {
            initialValue: protocolInfo.protocolTypeName,
          })(<Input disabled />)}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.protocol.info.nodetype' })}
          colon={false}
        >
          {form.getFieldDecorator('nodeTypeName', {
            initialValue: protocolInfo.nodeTypeName,
          })(<Input disabled />)}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.protocol.info.encoder' })}
          colon={false}
        >
          {form.getFieldDecorator('encoderId', {
            initialValue: protocolInfo.encoderId,
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({
                id: 'app.dm.product.protocol.info.encoder.place',
              })}
            >
              {renderOption(encoderList)}
            </Select>,
          )}
        </FormItem>

        <FormItem
          label={formatMessage({ id: 'app.dm.product.protocol.info.decoder' })}
          colon={false}
        >
          {form.getFieldDecorator('decoderId', {
            initialValue: protocolInfo.decoderId,
          })(
            <Select
              allowClear
              style={{ width: '100%' }}
              placeholder={formatMessage({
                id: 'app.dm.product.protocol.info.decoder.place',
              })}
            >
              {renderOption(decoderList)}
            </Select>,
          )}
        </FormItem>

        <FormItem label={formatMessage({ id: 'app.dm.product.info.more.desc' })} colon={false}>
          {form.getFieldDecorator('desc', {
            rules: [],
            initialValue: protocolInfo.desc,
          })(<TextArea rows={4} />)}
        </FormItem>
      </div>
    </Modal>
  );
});

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
class ProductProtocolInfo extends PureComponent {
  state = {
    modalVisible: false,
  };

  componentDidMount() {
    const { dispatch, params } = this.props;
    dispatch({
      type: 'product/fetchProtocol',
      payload: params.id,
    });
    dispatch({
      type: 'product/fetchDecoder',
    });
    dispatch({
      type: 'product/fetchEncoder',
    });
  }

  handleEdit = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'product/editProtocol',
      payload: {
        id: fields.id,
        productId: fields.productId,
        name: fields.name,
        encoderId: fields.encoderId,
        decoderId: fields.decoderId,
        desc: fields.desc,
      },
      form,
      handleModalVisible,
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  render() {
    const {
      product: { protocolInfo, encoder, decoder },
    } = this.props;

    const showType = val => {
      if (val === 1) {
        return formatMessage({ id: 'app.dm.product.info.type.device' });
      }
      if (val === 2) {
        return formatMessage({ id: 'app.dm.product.info.type.gateway' });
      }
      return null;
    };

    const showProtocol = val => {
      if (val === 1) {
        return formatMessage({ id: 'app.dm.product.info.netdata.mqtt' });
      }
      if (val === 2) {
        return formatMessage({ id: 'app.dm.product.info.netdata.tcpip' });
      }
      if (val === 3) {
        return formatMessage({ id: 'app.dm.product.info.netdata.modbustcp' });
      }
      return null;
    };

    const edit = (id, flag) => {
      this.setState({
        modalVisible: !!flag,
      });
    };

    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      handleEdit: this.handleEdit,
      protocolInfo,
      encoderList: encoder,
      decoderList: decoder,
    };

    const { modalVisible } = this.state;

    return (
      <Fragment>
        <Row style={{ textAlign: 'right' }}>
          <Button onClick={() => edit(protocolInfo.id, true)} type="primary">
            <FormattedMessage id="app.dm.product.protocol.info.edit" />
          </Button>
        </Row>
        <Row style={{ marginTop: 15 }}>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.name" />
          </Col>
          <Col className={styles.info_con} span={5}>
            {protocolInfo.name}
          </Col>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.label" />
          </Col>
          <Col className={styles.info_con} span={5}>
            {protocolInfo.label}
          </Col>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.createtime" />
          </Col>
          <Col className={styles.info_con_end} span={5}>
            {protocolInfo.createTime}
          </Col>
        </Row>
        <Row>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.protocoltype" />
          </Col>
          <Col className={styles.info_con} span={5}>
            {showProtocol(protocolInfo.protocolType)}
          </Col>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.nodetype" />
          </Col>
          <Col className={styles.info_con} span={5}>
            {showType(protocolInfo.nodeType)}
          </Col>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.encoder" />
          </Col>
          <Col className={styles.info_con_end} span={5}>
            {protocolInfo.encoderName}
          </Col>
        </Row>
        <Row>
          <Col className={styles.info_item} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.decoder" />
          </Col>
          <Col className={styles.info_con} span={5}>
            {protocolInfo.decoderName}
          </Col>
          <Col className={styles.info_item_bottom} span={3}>
            <FormattedMessage id="app.dm.product.protocol.info.desc" />
          </Col>
          <Col className={styles.info_con_end_bottom} span={13}>
            {protocolInfo.desc}
          </Col>
        </Row>
        <EditForm {...parentMethods} modalVisible={modalVisible} />
      </Fragment>
    );
  }
}

export default ProductProtocolInfo;
